// pages/team-info/team-info.js
import { queryProjectService, 
  queryApplicationProjectService 
} from "../../api/project";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    teamInfo: null,
    loading: true,
    projectId: null,
    applicationId: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("接收到的参数:", options);

    // 修改参数接收逻辑，支持多种参数传递方式
    let { projectId, applicationId, id } = options;

    // 如果没有projectId，尝试使用id作为projectId
    if (!projectId && id) {
      projectId = id;
    }

    // 放宽参数验证，只要有projectId就可以尝试获取信息
    if (!projectId) {
      wx.showModal({
        title: "参数错误",
        content: "缺少项目ID参数，无法获取小队信息",
        showCancel: false,
        confirmText: "返回",
        success: () => {
          wx.navigateBack();
        },
      });
      return;
    }

    this.setData({
      projectId: projectId,
      applicationId: applicationId || null, // applicationId可以为空
    });

    this.loadTeamInfo();
  },

  /**
   * 获取认证头
   */
  getAuthHeader() {
    const token = wx.getStorageSync("token");

    if (token) {
      return {
        "content-type": "application/json",
        Authorization: token,
      };
    } else {
      return {
        "content-type": "application/json",
      };
    }
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const token = wx.getStorageSync("token");

    if (!token) {
      wx.showModal({
        title: "提示",
        content: "请先登录",
        showCancel: true,
        cancelText: "取消",
        confirmText: "去登录",
        success: (res) => {
          if (res.confirm) {
            wx.redirectTo({
              url: "/pages/login/login",
            });
          }
        },
      });
      return false;
    }
    return true;
  },

  /**
   * 加载小队信息
   */
  loadTeamInfo() {
    if (!this.checkLoginStatus()) {
      return;
    }

    wx.showLoading({
      title: "加载中...",
    });

    // 修改接口调用逻辑，优先尝试获取项目详情和联系信息
    this.getProjectDetail();
  },

  /**
   * 获取项目详情
   */
  getProjectDetail() {
    // 先尝试获取项目基本信息
    queryProjectService({
      pageNum: "1",
      pageSize: "100",
    })
      .then((res) => {
        console.log("获取项目列表响应:", res);

        if (res.code === 200 && res.data) {
          const projects = res.data || [];
          const targetProject = projects.find(
            (item) =>
              item.id && item.id.toString() === this.data.projectId.toString(),
          );

          if (targetProject) {
            // 找到项目后，获取申请信息以获取联系方式
            this.getApplicationInfo(targetProject);
          } else {
            // 如果在项目列表中没找到，尝试从申请记录中获取
            this.getApplicationProject();
          }
        } else {
          this.getApplicationProject(); // 备用方案
        }
      })
      .catch((err) => {
        console.error("获取项目详情失败:", err);
        this.getApplicationProject(); // 备用方案
      });
  },

  /**
   * 获取申请信息（包含联系方式）
   */
  getApplicationInfo(projectInfo) {
    queryApplicationProjectService({
      pageNum: "1",
      pageSize: "100",
    })
      .then((res) => {
        wx.hideLoading();

        console.log("获取申请信息响应:", res);

        if (res.code === 200 && res.data) {
          const applications = res.data || [];
          const targetApplication = applications.find(
            (item) =>
              item.project &&
              item.project.id.toString() === this.data.projectId.toString(),
          );

          if (targetApplication && targetApplication.isApproved === 1) {
            // 合并项目信息和联系信息
            this.setData({
              teamInfo: {
                // 项目信息
                projectId: projectInfo.id,
                projectName: projectInfo.projectName,
                projectInfo: projectInfo.projectInfo,
                school: projectInfo.school,
                direction: this.getDirectionText(projectInfo.direction),
                memberCount: projectInfo.memberCount,
                crossSchool: projectInfo.crossSchool === 1,
                educationRequirement: projectInfo.educationRequirement,
                skillSummary: projectInfo.skillSummary,
                skillDetails: projectInfo.skillDetails,
                createdAt: projectInfo.createdAt,

                // 组织者联系信息（审核通过才有）
                phone: targetApplication.phone,
                email: targetApplication.email,
                nickname: targetApplication.nickname,

                // 审核信息
                isApproved: targetApplication.isApproved,
                approveReason: targetApplication.approveReason,
                approveTime: targetApplication.approveTime,
              },
              loading: false,
            });
          } else {
            // 使用项目基本信息，但没有联系方式
            this.setData({
              teamInfo: {
                projectId: projectInfo.id,
                projectName: projectInfo.projectName,
                projectInfo: projectInfo.projectInfo,
                school: projectInfo.school,
                direction: this.getDirectionText(projectInfo.direction),
                memberCount: projectInfo.memberCount,
                crossSchool: projectInfo.crossSchool === 1,
                educationRequirement: projectInfo.educationRequirement,
                skillSummary: projectInfo.skillSummary,
                skillDetails: projectInfo.skillDetails,
                createdAt: projectInfo.createdAt,

                // 没有联系信息
                phone: null,
                email: null,
                nickname: null,
                isApproved: 0,
              },
              loading: false,
            });
          }
        } else {
          // 只显示项目基本信息
          this.setData({
            teamInfo: {
              projectId: projectInfo.id,
              projectName: projectInfo.projectName,
              projectInfo: projectInfo.projectInfo,
              school: projectInfo.school,
              direction: this.getDirectionText(projectInfo.direction),
              memberCount: projectInfo.memberCount,
              crossSchool: projectInfo.crossSchool === 1,
              educationRequirement: projectInfo.educationRequirement,
              skillSummary: projectInfo.skillSummary,
              skillDetails: projectInfo.skillDetails,
              createdAt: projectInfo.createdAt,

              phone: null,
              email: null,
              nickname: null,
              isApproved: 0,
            },
            loading: false,
          });
        }
      })
      .catch((err) => {
        wx.hideLoading();
        console.error("获取申请信息失败:", err);
        // 只显示项目基本信息
        this.setData({
          teamInfo: {
            projectId: projectInfo.id,
            projectName: projectInfo.projectName,
            projectInfo: projectInfo.projectInfo,
            school: projectInfo.school,
            direction: this.getDirectionText(projectInfo.direction),
            memberCount: projectInfo.memberCount,
            crossSchool: projectInfo.crossSchool === 1,
            educationRequirement: projectInfo.educationRequirement,
            skillSummary: projectInfo.skillSummary,
            skillDetails: projectInfo.skillDetails,
            createdAt: projectInfo.createdAt,

            phone: null,
            email: null,
            nickname: null,
            isApproved: 0,
          },
          loading: false,
        });
      });
  },

  /**
   * 备用方案：从申请记录中获取信息
   */
  getApplicationProject() {
    queryApplicationProjectService({
      pageNum: "1",
      pageSize: "100",
    })
      .then((res) => {
        wx.hideLoading();

        console.log("获取申请记录响应:", res);

        if (res.code === 200 && res.data) {
          const responseData = res.data || [];

          const targetApplication = responseData.find(
            (item) =>
              item.project &&
              item.project.id.toString() === this.data.projectId.toString(),
          );

          if (targetApplication) {
            this.setData({
              teamInfo: {
                // 项目信息
                projectId: targetApplication.project.id,
                projectName: targetApplication.project.projectName,
                projectInfo: targetApplication.project.projectInfo,
                school: targetApplication.project.school,
                schoolname: targetApplication.project.schoolname,
                direction: this.getDirectionText(targetApplication.project.direction),
                memberCount: targetApplication.project.memberCount,
                crossSchool: targetApplication.project.crossSchool === 1,
                educationRequirement:
                  targetApplication.project.educationRequirement,
                skillSummary: targetApplication.project.skillSummary,
                skillDetails: targetApplication.project.skillDetails,
                createdAt: targetApplication.project.createdAt,

                // 组织者联系信息
                phone: targetApplication.phone,
                email: targetApplication.email,
                nickname: targetApplication.nickname,

                // 审核信息
                isApproved: targetApplication.isApproved,
                approveReason: targetApplication.approveReason,
                approveTime: targetApplication.approveTime,
              },
              loading: false,
            });
          } else {
            this.handleError("未找到对应的项目信息");
          }
        } else {
          this.handleError(res.message || "获取数据失败");
        }
      })
      .catch((err) => {
        wx.hideLoading();
        console.error("请求失败:", err);
        this.handleError("网络连接异常，请重试");
      });
  },

  /**
   * 处理错误
   */
  handleError(message) {
    this.setData({
      loading: false,
    });

    wx.showModal({
      title: "加载失败",
      content: message,
      showCancel: true,
      cancelText: "返回",
      confirmText: "重试",
      success: (res) => {
        if (res.confirm) {
          this.setData({ loading: true });
          this.loadTeamInfo();
        } else {
          wx.navigateBack();
        }
      },
    });
  },

  /**
   * 拨打电话
   */
  makePhoneCall(e) {
    const phone = e.currentTarget.dataset.phone;

    if (!phone) {
      wx.showToast({
        title: "电话号码不可用",
        icon: "none",
      });
      return;
    }

    wx.showModal({
      title: "拨打电话",
      content: `确定要拨打电话：${phone} 吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: phone,
            fail: (err) => {
              console.error("拨打电话失败:", err);
              wx.showToast({
                title: "拨打电话失败",
                icon: "error",
              });
            },
          });
        }
      },
    });
  },

  /**
   * 复制邮箱
   */
  copyEmail(e) {
    const email = e.currentTarget.dataset.email;

    if (!email) {
      wx.showToast({
        title: "邮箱地址不可用",
        icon: "none",
      });
      return;
    }

    wx.setClipboardData({
      data: email,
      success: () => {
        wx.showToast({
          title: "邮箱已复制",
          icon: "success",
        });
      },
      fail: () => {
        wx.showToast({
          title: "复制失败",
          icon: "error",
        });
      },
    });
  },

  /**
   * 复制手机号
   */
  copyPhone(e) {
    const phone = e.currentTarget.dataset.phone;

    if (!phone) {
      wx.showToast({
        title: "电话号码不可用",
        icon: "none",
      });
      return;
    }

    wx.setClipboardData({
      data: phone,
      success: () => {
        wx.showToast({
          title: "电话号码已复制",
          icon: "success",
        });
      },
      fail: () => {
        wx.showToast({
          title: "复制失败",
          icon: "error",
        });
      },
    });
  },

  /**
   * 查看项目详情
   */
  viewProjectDetail() {
    const teamInfo = this.data.teamInfo;

    const content = `项目名称：${teamInfo.projectName}
项目介绍：${teamInfo.projectInfo}
学校：${teamInfo.schoolname}
方向：${teamInfo.direction}
成员数量：${teamInfo.memberCount}
跨校合作：${teamInfo.crossSchool ? "是" : "否"}
学历要求：${this.getEducationRequirementText(teamInfo.educationRequirement)}
技能要求：${teamInfo.skillDetails}`;

    wx.showModal({
      title: "项目详情",
      content: content,
      showCancel: false,
      confirmText: "我知道了",
    });
  },

  /**
   * 方向数字转文字
   */
  getDirectionText(direction) {
    switch (Number(direction)) {
      case 1:
        return "落地";
      case 2:
        return "获奖";
      case 3:
        return "学习";
      default:
        return "落地";
    }
  },

  /**
   * 学历要求数字转文字
   */
  getEducationRequirementText(educationRequirement) {
    switch (Number(educationRequirement)) {
      case 1:
        return "大专";
      case 2:
        return "本科";
      case 3:
        return "研究生";
      case 4:
        return "博士";
      default:
        return "不限";
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadTeamInfo();
    wx.stopPullDownRefresh();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});